home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 10 directories, files, and streams / dirfiledemo / module1.vb < prev   
Encoding:
Text File  |  2002-03-20  |  17.0 KB  |  445 lines

  1. Imports System.Globalization
  2. Imports System.IO
  3. Imports Microsoft.Win32
  4.  
  5. Module MainModule
  6.  
  7.     Sub Main()
  8.         ' Run one of the Textxxxx procedures below by uncommenting only one statement
  9.  
  10.         'TestFileDirectory()
  11.         'TestFileDirectoryInfo()
  12.         'TestPath()
  13.         'TestStreamReader()
  14.         'TestStreamWriter()
  15.         'TestBinaryReaderWriter()
  16.         'TestMemoryStream()
  17.         'TestStringReaderWriter()
  18.         'TestCustomBinaryReaderWriter()
  19.  
  20.         ' These statements are usuful when running inside Visual Studio.NET
  21.         Console.WriteLine("")
  22.         Console.WriteLine(">>> Press Enter to terminate the program <<<")
  23.         Console.ReadLine()
  24.     End Sub
  25.  
  26.     ' this procedure tests the File and Directory objects
  27.  
  28.     Sub TestFileDirectory()
  29.         ' Save the current directory.
  30.         Dim currDir As String = Directory.GetCurrentDirectory
  31.         ' Change the current directory to something else.
  32.         Directory.SetCurrentDirectory("C:\")
  33.         ' check that it worked
  34.         Console.WriteLine("Current directory: " & Directory.GetCurrentDirectory)
  35.         ' Restore the current directory.
  36.         Directory.SetCurrentDirectory(currDir)
  37.  
  38.         ' Retrieve all the root paths.
  39.         Dim strRoots() As String = Directory.GetLogicalDrives
  40.         Dim s As String
  41.         For Each s In strRoots
  42.             Console.WriteLine(s)         ' => C:\  D:\  ...
  43.         Next
  44.  
  45.         ' display files and directories in C:\DOCS
  46.         PrintDirTree("c:\docs", True)
  47.  
  48.         ' Display all the *.txt files in C:\DOCS.
  49.         Dim fname As String
  50.         For Each fname In Directory.GetFiles("c:\docs", "*.txt")
  51.             Console.WriteLine(fname)
  52.         Next
  53.         Console.WriteLine("")
  54.  
  55.         ' Display system and hidden files in C:\.
  56.         For Each fname In Directory.GetFiles("C:\")
  57.             Dim attr As FileAttributes = File.GetAttributes(fname)
  58.             ' Show the file if it is marked as either hidden or system (or both).
  59.             If CBool(attr And FileAttributes.Hidden) Or CBool(attr And FileAttributes.System) Then
  60.                 ' NOTE: you can make the IF condition more concise as follows:
  61.                 'If CBool(attr And (FileAttributes.Hidden Or FileAttributes.System)) Then
  62.                 Console.WriteLine(fname)
  63.             End If
  64.         Next
  65.  
  66.         ' ensure that we aren't destroying an existing directory tree
  67.         If Not Directory.Exists("c:\myapp") Then
  68.             ' Next line works even if the C:\MyApp directory doesn't exist yet.
  69.             Directory.CreateDirectory("C:\MyApp\Data")
  70.             ' check that it worked
  71.             If Directory.Exists("c:\myapp\data") Then
  72.                 Console.WriteLine("The C:\MYAPP\DATA directory has been created.")
  73.             End If
  74.             ' delete it, forcing deletion of inner directories
  75.             Directory.Delete("c:\MyApp", True)
  76.         End If
  77.  
  78.         ' Change the access date-time of all files in C:\DOCS.
  79.         For Each fname In Directory.GetFiles("c:\docs", "*.txt")
  80.             File.SetLastAccessTime(fname, Date.Now)
  81.         Next
  82.  
  83.         ' a "touch" utility 
  84.         ' NOTE: test by running from command prompt and passing one more more file names
  85.         For Each fname In Environment.GetCommandLineArgs
  86.             File.SetCreationTime(fname, Date.Now)
  87.         Next
  88.     End Sub
  89.  
  90.     ' traverse a directory tree
  91.  
  92.     Sub PrintDirTree(ByVal dir As String, ByVal showFiles As Boolean, _
  93.     Optional ByVal level As Integer = 0)
  94.         Dim subdir As String
  95.         Dim fname As String
  96.  
  97.         ' Display the name of this directory with correct indentation.
  98.         Console.WriteLine(New String("-"c, level * 2) & dir)
  99.  
  100.         Try
  101.             ' Display all files in this directory, with correct indentation.
  102.             If showFiles Then
  103.                 For Each fname In Directory.GetFiles(dir)
  104.                     Console.WriteLine(New String(" "c, level * 2 + 2) & fname)
  105.                 Next
  106.             End If
  107.             ' A recursive call for all the subdirectories in this directory.
  108.             For Each subdir In Directory.GetDirectories(dir)
  109.                 PrintDirTree(subdir, showFiles, level + 1)
  110.             Next
  111.         Catch
  112.             ' Do nothing if any error (presumably "Drive not ready").
  113.         End Try
  114.     End Sub
  115.  
  116.     ' test DirectoryInfo or FileInfo classes
  117.  
  118.     Sub TestFileDirectoryInfo()
  119.         ' Create a DirectoryInfo object that points to C:\.
  120.         Dim rootDi As New DirectoryInfo("C:\")
  121.         ' Create a FileInfo object that points to C:\Autoexec.bat.
  122.         Dim fi As New FileInfo("C:\Autoexec.bat")
  123.  
  124.         ' List the directories in C:\.
  125.         Dim di As DirectoryInfo
  126.         For Each di In rootDi.GetDirectories
  127.             Console.WriteLine(di.Name)
  128.         Next
  129.         Console.WriteLine("")
  130.  
  131.         ' List all the *.txt files in C:\.
  132.         For Each fi In rootDi.GetFiles("*.txt")
  133.             Console.WriteLine(fi.Name)
  134.         Next
  135.         Console.WriteLine("")
  136.  
  137.         Dim fsi As FileSystemInfo
  138.  
  139.         ' Display all files and subdirectories in C:\
  140.         ' Note that we can create the DirectoryInfo object on-the-fly.
  141.         For Each fsi In (New DirectoryInfo("C:\")).GetFileSystemInfos
  142.             ' Use a [dir] or [file] prefix.
  143.             If CBool(fsi.Attributes And FileAttributes.Directory) Then
  144.                 Console.Write("[dir] ")
  145.             Else
  146.                 Console.Write("[file] ")
  147.             End If
  148.             ' Print name and creation date
  149.             Console.WriteLine(fsi.Name & " - " & fsi.CreationTime)
  150.         Next
  151.     End Sub
  152.  
  153.     ' this procedure tests the Path class
  154.  
  155.     Sub TestPath()
  156.         Console.WriteLine(Path.AltDirectorySeparatorChar)  ' => /
  157.         Console.WriteLine(Path.DirectorySeparatorChar)     ' => \
  158.         Console.WriteLine(Path.InvalidPathChars)           ' => "<>|
  159.         Console.WriteLine(Path.PathSeparator)              ' => ;
  160.         Console.WriteLine(Path.VolumeSeparatorChar)        ' => :
  161.  
  162.         ' Note that paths are in 8.3 MsDos format.
  163.         Console.WriteLine(Path.GetTempPath)
  164.         ' => C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
  165.         Console.WriteLine(Path.GetTempFileName)
  166.         ' => C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\tmp1B2.tmp
  167.  
  168.         Dim fil As String = "C:\MyApp\Bin\MyApp.exe"
  169.         Console.WriteLine(Path.GetDirectoryName(fil))            ' => C:\MyApp\Bin
  170.         Console.WriteLine(Path.GetFileName(fil))                 ' => MyApp.exe
  171.         Console.WriteLine(Path.GetExtension(fil))                ' => .exe
  172.         Console.WriteLine(Path.GetFileNameWithoutExtension(fil)) ' => MyApp
  173.         Console.WriteLine(Path.GetPathRoot(fil))                 ' => C:\
  174.         Console.WriteLine(Path.HasExtension(fil))                ' => True
  175.         Console.WriteLine(Path.IsPathRooted(fil))                ' => True
  176.  
  177.         ' Next line assumes that current directory is C:\MyApp.
  178.         Console.WriteLine(Path.GetFullPath("MyApp.Exe"))   ' => C:\MyApp\MyApp.Exe
  179.  
  180.         Console.WriteLine(Path.ChangeExtension("MyApp.Exe", "Dat"))  ' => MyApp.Dat
  181.  
  182.         Console.WriteLine(Path.Combine("C:\MyApp\", "MyApp.Dat"))
  183.         ' => C:\MyApp\MyApp.Dat
  184.     End Sub
  185.  
  186.     ' this procedure tests StreamReader objects
  187.  
  188.     Sub TestStreamReader()
  189.         ' The File.OpenText shared method.
  190.         Dim sr As StreamReader = File.OpenText("c:\autoexec.bat")
  191.  
  192.         ' the following block of code include alternative 
  193.         ' open tecniques , as described in the book
  194.  
  195. #If False Then
  196.         ' The OpenText instance method of a FileInfo object.
  197.         Dim fi2 As New FileInfo("c:\autoexec.bat")
  198.         Dim sr2 As StreamReader = fi2.OpenText
  199.  
  200.         ' By passing a FileStream from the Open method of File class to
  201.         ' the StreamReader's constructor method.
  202.         ' (This technique lets you specify mode, access, and share mode.)
  203.         Dim st3 As Stream = File.Open("C:\autoexec.bat", _
  204.             FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
  205.         Dim sr3 As New StreamReader(st3)
  206.  
  207.         ' By opening a FileStream on the file, and then passing it
  208.         ' to the StreamReader's constructor method.
  209.         Dim fs4 As New FileStream("C:\autoexec.bat", FileMode.Open)
  210.         Dim sr4 As New StreamReader(fs4)
  211.  
  212.         ' By getting a FileStream from the OpenRead method of File class
  213.         ' and passing it to the StreamReader's constructor.
  214.         Dim sr5 As New StreamReader(File.OpenRead("c:\autoexec.bat"))
  215.  
  216.         ' By passing the file name to the StreamReader's constructor.
  217.         Dim sr6 As New StreamReader("c:\autoexec.bat")
  218.  
  219.         ' By passing the file name and encoding.
  220.         Dim sr7 As New StreamReader("c:\autoexec.bat", System.Text.Encoding.Unicode)
  221.         Dim sr8 As New StreamReader("c:\autoexec.bat", System.Text.Encoding.ASCII)
  222.         ' As before, but we let the system decide the best encoding.
  223.         Dim sr9 As New StreamReader("c:\autoexec.bat", True)
  224. #End If
  225.  
  226.         ' Display all the text lines in the file.
  227.         Do Until sr.Peek = -1
  228.             ' The ReadLine methods reads whole lines.
  229.             Console.WriteLine(sr.ReadLine)
  230.         Loop
  231.         ' Always close a StreamReader when you've done with it.
  232.         sr.Close()
  233.  
  234.         ' Read the entire contents of C:\Autoexec.bat in one shot.
  235.         sr = New StreamReader("c:\autoexec.bat")
  236.         Dim fileContents As String = sr.ReadToEnd()
  237.         Console.WriteLine(fileContents)
  238.         Console.WriteLine("")
  239.  
  240.         ' If the file contains "WARNING" then process it again, one character at a 
  241.         ' time (admittedly a silly thing to do, but it's just a demo).
  242.         If fileContents.Length >= 10 Then
  243.             ' Reset the stream's pointer to the beginning.
  244.             sr.BaseStream.Seek(0, SeekOrigin.Begin)
  245.             ' Read individual characters until EOF is reached.
  246.             Do Until sr.Peek() = -1
  247.                 ' Read returns an integer, convert it to Char.
  248.                 Console.Write(sr.Read.ToString)
  249.             Loop
  250.         End If
  251.         sr.Close()
  252.         Console.WriteLine("")
  253.     End Sub
  254.  
  255.     ' this procedure tests StreamWriter objects
  256.  
  257.     Sub TestStreamWriter()
  258.  
  259.         ' skip over alternative open tecniques in this demo
  260. #If False Then
  261.         ' The File class's CreateText or AppendText methods (shared or instance).
  262.         Dim sw1 As StreamWriter = File.CreateText("c:\temp.dat")
  263.  
  264.         ' By passing a FileStream from the Open method of File class to
  265.         ' the StreamWriter's constructor method.
  266.         Dim st2 As Stream = File.Open("C:\temp.dat", _
  267.             FileMode.Create, FileAccess.ReadWrite, FileShare.None)
  268.         Dim sw2 As New StreamWriter(st2)
  269.  
  270.         ' By opening a FileStream on the file, and then passing it
  271.         ' to the StreamWriter's constructor method.
  272.         Dim fs3 As New FileStream("C:\autoexec.bat", FileMode.Open)
  273.         Dim sw3 As New StreamWriter(fs3)
  274.  
  275.         ' By getting a FileStream from the OpenWrite method of File class
  276.         ' and passing it to the StreamWriter's constructor.
  277.         Dim sw4 As New StreamWriter(File.OpenWrite("C:\temp.dat"))
  278.  
  279.         ' By passing the file name to the StreamWriter's constructor.
  280.         Dim sw5 As New StreamWriter("C:\temp.dat")
  281. #End If
  282.  
  283.         ' Copy C:\Autoexec.bat to C:\Autoexec.new, and covert chars to uppercase.
  284.         Dim sr As New StreamReader("C:\Autoexec.bat")
  285.         Dim sw As New StreamWriter("C:\Autoexec.new")
  286.  
  287.         Do Until sr.Peek = -1
  288.             ' The ReadLine method returns a string, so we can
  289.             ' convert it to uppercase on the fly.
  290.             sw.WriteLine(sr.ReadLine.ToUpper)
  291.         Loop
  292.         sr.Close()
  293.         sw.Close()      ' This actually writes data to file and closes it.
  294.  
  295.         ' do it again in one operation
  296.         sr = New StreamReader("C:\Autoexec.bat")
  297.         sw = New StreamWriter("C:\Autoexec.new")
  298.         sw.Write(sr.ReadToEnd.ToUpper)
  299.         sr.Close()
  300.         sw.Close()
  301.     End Sub
  302.  
  303.     ' this procedure tests the BinaryReader and BinaryWriter classes
  304.  
  305.     Sub TestBinaryReaderWriter()
  306.         ' Associate a stream to a new file, opened with write access. 
  307.         Dim st As Stream = File.Open("c:\values.dat", FileMode.Create, FileAccess.Write)
  308.         ' Create a BinaryWriter associated to the output stream.
  309.         Dim bw As New BinaryWriter(st)
  310.  
  311.         Dim i As Integer, rand As New Random()
  312.         For i = 1 To 10
  313.             bw.Write(rand.NextDouble)
  314.         Next
  315.         ' Flush the output data to the file.
  316.         bw.Close()
  317.         st.Close()
  318.  
  319.         ' Read back values written in previous example.
  320.  
  321.         ' Associate a stream to an existing file, opened with read access. 
  322.         Dim st2 As Stream = File.Open("c:\values.dat", FileMode.Open, FileAccess.Read)
  323.         ' Create a BinaryReader associated to the input stream.
  324.         Dim br2 As New BinaryReader(st2)
  325.  
  326.         ' Loop until there is data avaialble.
  327.         Do Until br2.PeekChar = -1
  328.             ' Read the next element.
  329.             Console.WriteLine(br2.ReadDouble)
  330.         Loop
  331.         br2.Close()
  332.         st2.Close()
  333.     End Sub
  334.  
  335.     ' this procedure tests the MemoryStream object
  336.  
  337.     Sub TestMemoryStream()
  338.         ' Create a memory stream with initial capacity of 1K.
  339.         Dim st As New MemoryStream(1024)
  340.         Dim bw As New BinaryWriter(st)
  341.         Dim i As Integer, rand As New Random()
  342.         ' Write 10 random Double values to the stream.
  343.         For i = 1 To 10
  344.             bw.Write(rand.NextDouble)
  345.         Next
  346.  
  347.         ' Rewind the stream to the beginning.
  348.         st.Seek(0, SeekOrigin.Begin)
  349.         Dim br As New BinaryReader(st)
  350.  
  351.         Do Until br.PeekChar = -1
  352.             Console.WriteLine(br.ReadDouble)
  353.         Loop
  354.         br.Close()
  355.         st.Close()
  356.  
  357.         ' Write two strings to a MemoryStream.        
  358.         st = New MemoryStream(1000)
  359.         bw = New BinaryWriter(st)
  360.         bw.Write("length-prefixed string")
  361.  
  362.         ' we'll use for both reading and writing
  363.         Dim buffer(1024) As Char                    'a 1K buffer
  364.  
  365.         Dim s As String = "13 Characters"           ' fixed-length string
  366.         s.CopyTo(0, buffer, 0, 13)                  ' copy into the buffer
  367.         bw.Write(buffer, 0, 13)                     ' output first 13 chars in buffer
  368.         bw.Write(buffer, 0, 13)                     ' do it twice
  369.  
  370.         ' Rewind the stream, and prepare to read from it.
  371.         st.Seek(0, SeekOrigin.Begin)
  372.         br = New BinaryReader(st)
  373.         ' Reading the length-prefixed string is easy.
  374.         Console.WriteLine(br.ReadString)            ' => length-prefixed string
  375.  
  376.         ' Read the fixed-length string into the buffer
  377.         br.Read(buffer, 0, 13)                      ' Read 13 characters.
  378.         s = New String(buffer, 0, 13)               ' convert to a string
  379.         Console.WriteLine(s)                        ' => 13 Characters
  380.  
  381.         ' Another way to read a fixed-length string
  382.         s = New String(br.ReadChars(13))
  383.         Console.WriteLine(s)                        ' => 13 Characters
  384.     End Sub
  385.  
  386.     ' this procedure tests StringReader and StringWriter classes
  387.  
  388.     Sub TestStringReaderWriter()
  389.         Dim veryLongString As String
  390.         ' initialize this variable with the contents of Autoexec.bat
  391.         Dim sr As New StreamReader("c:\autoexec.bat")
  392.         veryLongString = sr.ReadToEnd
  393.         sr.Close()
  394.  
  395.         ' The veryLongString variable contains the text to parse.
  396.         Dim strReader As New StringReader(veryLongString)
  397.         ' Display individual lines of text.
  398.         Do Until strReader.Peek = -1
  399.             Console.WriteLine(strReader.ReadLine)
  400.         Loop
  401.  
  402.         ' Create a string with the space-separated abbreviated names of weekdays.
  403.         ' A StringBuilder of 7*4 characters is enough.
  404.         Dim sb As New System.Text.StringBuilder(28)
  405.         ' The StringWriter associated to the StringBuilder.
  406.         Dim strWriter As New StringWriter(sb)
  407.  
  408.         ' Output day names to the string.
  409.         Dim d As String
  410.         For Each d In DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames
  411.             strWriter.Write(d)
  412.             strWriter.Write(" ")        ' Append a space.
  413.         Next
  414.         Console.WriteLine(sb)           ' => Sun Mon Tue Wed Thu Fri Sat
  415.     End Sub
  416.  
  417.     ' this procedure tests custom BinaryReaderEx and BinaryWriterEx classes
  418.  
  419.     Sub TestCustomBinaryReaderWriter()
  420.         Dim st As New MemoryStream(1000)
  421.         Dim bw As New BinaryWriterEx(st)
  422.  
  423.         ' Write a Person object, then a รป1 value (short).
  424.         Dim p As New Person("Joe", "Doe")
  425.         bw.Write(p)
  426.         bw.Write(-1S)
  427.  
  428.         ' Rewind the stream, and prepare to read from it.
  429.         st.Seek(0, SeekOrigin.Begin)
  430.         Dim br As New BinaryReaderEx(st)
  431.  
  432.         ' Read a Person object, and prove that properties have been preserved.
  433.         Dim p2 As Person = br.ReadPerson()
  434.         Console.WriteLine(p.FirstName & " " & p.LastName)
  435.         ' Read the Short value.
  436.         Console.WriteLine(br.ReadInt16)
  437.  
  438.         ' Clean up
  439.         bw.Close()
  440.         br.Close()
  441.         st.Close()
  442.     End Sub
  443.  
  444. End Module
  445.